package com.zuo.listener;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.log4j.Logger;

import com.zuo.model.LoginModel;

public class LoginListener implements HttpSessionListener, HttpSessionAttributeListener {

	public static Map<String, HttpSession> sessionMap = new HashMap<String, HttpSession>();
	static Logger logger = Logger.getLogger(LoginListener.class.getName());

	@Override
	public void attributeAdded(HttpSessionBindingEvent se) {

		if ("loginModel".equals(se.getName())) {
			LoginModel u = (LoginModel) se.getValue();
			logger.info("监测创建session被放入loginModel,取出的username：" + u.getUsername());
			HttpSession session = sessionMap.remove(u.getUsername());
			if (session != null) {
				logger.info("前用户已挤掉");
				String message = "您的账号已经在其它客服端登录";
				session.setAttribute("mssg", message);
				// session.removeAttribute("loginModel");
			}
			sessionMap.put(u.getUsername(), se.getSession());
			logger.info("map添加了新的session" + sessionMap.get(u.getUsername()).getId());
		}
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent se) {
		if ("loginModel".equals(se.getName())) {
			logger.info("监测到loginmodel被移除");
			try {
				LoginModel u = (LoginModel) se.getValue();
				sessionMap.remove(u.getUsername());
				logger.info("sessionmap移除了:" + u.getUsername());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent se) {
		if ("loginModel".equals(se.getName())) {
			logger.info("监测到session有覆盖更新");
			LoginModel u = (LoginModel) se.getValue();
			HttpSession see = sessionMap.remove(u.getUsername());
			sessionMap.put(u.getUsername(), se.getSession());
		}

	}

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		logger.info("监测到客户请求服务器，创建了session,sessionId是" + se.getSession().getId());
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {

		try {
			logger.info("监测到sessionId是" + se.getSession().getId() + "被销毁");
			if(se.getSession().getAttribute("loginModel")!=null){
			LoginModel u = (LoginModel) se.getSession().getAttribute("loginModel");
			System.out.println(u.getUsername());
			System.out.println("打印名字是" + u.getUsername());
			logger.info("取到了model u,准备打印名字");
			logger.info("打印名字是" + u.getUsername());
			sessionMap.remove(u.getUsername());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
